package com.jingdianjichi.auth.application.context;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Map;

/**
 * 登录上下文对象
 * @author 86156
 * @version 1.0
 * @date 2024-11-10 18:20
 */
public class LoginContextHolder {

    // 相比于ThreadLocal来说, 子线程可以继承父线程的内容
    private static final InheritableThreadLocal<Map<String,Object>> THREAD_LOCAL =
            new InheritableThreadLocal<>();

    public static void set(String key,Object value){
        Map<String, Object> map = getThreadLocalMap();
        map.put(key,value);
    }

    public static Map<String,Object> getThreadLocalMap(){
        Map<String, Object> map = THREAD_LOCAL.get();
        if(CollectionUtils.isEmpty(map)){
            map = new ConcurrentReferenceHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static Object get(String key){
        Map<String, Object> map = THREAD_LOCAL.get();
        return map.get(key);
    }

    public static void remove(){
        THREAD_LOCAL.remove();
    }

    public static String getLoginId(){
        return (String) THREAD_LOCAL.get().get("loginId");
    }

}
